export default {
	isdev: function(env) {
		var env = process.env.NODE_ENV;
		return env === 'developer' ? '/api' : '';
	},
	/*getIsLogin: function() {
		var backUrl = this.isdev() + "/user/checkLogin.htm",
			result;
		var data = this.$http.post({
			url: backUrl,
			type: 'POST',
			async: false,
			success: function(d) {
				result = d.result == 1 ? true : false;
			}
		});

		return result;
	},*/
	getLocation: function() {
		var pathname = window.location.pathname;
		var indexNext = pathname.indexOf("/", 0);
		return pathname.substr(0, indexNext);
	},
	goLogin: function() {
		window.location.href = this.getLocation() + "/user/toLogin.htm?targetUrl=" + encodeURIComponent(window.location.href);
	},
	setTitle:function(title) {
		  document.title = title;
		  var i = document.createElement('iframe');
		  //i.src = 'http://s1.cximg.com/msweb02/resource/comm/images/favicon.ico';
		  i.style.display = 'none';
		  i.onload = function() {
		    setTimeout(function(){
		      i.remove();
		    }, 9)
		  }
		  document.body.appendChild(i);

		  
		  
	},
	ANA_Analytics:function(){//埋点
		(new Analytics).scan();//打点CA绑定数据
		//埋点逻辑
	  var scriptBox = document.getElementById("analyticsScript");
	  var getLink = scriptBox.getAttribute('sr');
	  
	  if(scriptBox.getAttribute('src')){
	  	window.ANA.reconfig('').getDate().dataProcess().send();//埋点
	  }else{
	  	scriptBox.setAttribute("src",window._caProtocol + getLink + '?t=' + new Date().getTime());
	  }
		console.log('埋点再启动');
	},
	setTitle:function(titleValue){
		document.title = titleValue;

		const mobile = navigator.userAgent.toLowerCase();
		const length = document.querySelectorAll('iframe').length;

		if (/iphone|ipad|ipod/.test(mobile) && !length) {
			document.title = titleValue;
		  const iframe = document.createElement('iframe');
		  iframe.style.cssText = 'display: none; width: 0; height: 0;';
		  iframe.setAttribute('src', 'about:blank');
		  iframe.addEventListener('load', () => {
		    setTimeout(() => {
		      iframe.removeEventListener('load', false);
		      document.body.removeChild(iframe);
		    }, 0);
		  });
		  document.body.appendChild(iframe);
		}
	},
	isIOSWechat: function(){
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i)=="micromessenger" && ua.indexOf('iphone') > 0) {
			return true
		} else {
			return false
		}
	},
	setTitleAgain: function(titleValue, iframe){
		document.title = titleValue;
    // 判断是否为ios设备，ios设备需要通过加载iframe来刷新title
	    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
	      // iframe = '/favicon.ico?' + Math.random()	
	    }
	    return iframe;
	},
	carplateValidate: function(carplate) {
		var isPlate = /^[A-Z]{1}[A-Z_0-9]{6,7}$/; //车牌正则验证
		if(carplate) {
			if(!isPlate.test(carplate)) {
				Toast("车牌格式错误！");
				return false;
			}
		} else {
			Toast("亲，请填写车牌号！");
			return false;
		}

	},
		/**
		 * 验证登录
		 * @param {Object} url 当前登录地址
		 * @param {Object} cb  登陆成功回调函数
		 */
		//  checkLogin: function ( url, cb ) {
		//  	
		//  	var _result = this.getIsLogin();
		//  	
		//  }
	queryCodeMessage: function(res) {
		var code = res.errorCode || res.statusCode;
		var msgs = {
			"0001": "当前服务商品库存不足",
			"0002": "当前服务商品暂不可售", //商品不在购买期
			"0003": "当前服务商品暂不可售", //商品不在架
			"0004": "",//调用后台msg
			"0051": "",//调用后台msg
			"0052": "生产车辆资产ID出现异常",
			"0053": "获取会员信息失败",
			"0054": "获取会员等级失败",
			"0055": "转换预约时间异常",
			"0056": "联系人姓名为空",
			"0057": "请选择服务门店",
			"0058": "套餐卡号为空",
			"0059": "套餐卡服务无效",
			"0060": "商品S码为空",
			"0061": "查询出商品为渠道价",
			"0062": "服务车辆信息不存在",
			"0063": "商品强弱关联字段为null",
			"0064": "入参有误",
			"0065": "预约时间为空",
			"0066": "预约时间超过券有效期",
			"0067": "券信息不存在截止时间",
			"0068": "用户与券信息不匹配",
			"0069": ""//调用后台msg
			// "000001": "创建订单失败：获取订单头编号失败",
			// "000002": "创建订单失败：锁库存失败",
			// "000003": "创建订单失败：入参校验失败",
			// "000003": "结算价不能为空",
			// "000004": "创建订单失败：数据库执行异常",
			// "000005": "创建订单失败：锁券码失败",
			// "000006": "创建订单失败：锁套餐卡次数码失败",
			// "000008": "订单类型转换失败",
			// "000009": "创建订单并支付成功",
			// "000010": "创建订单成功支付失败"
		};
		var msg_back = '';
		if(!!res.msg) {
			msg_back=msgs[code];
		} else if (!!res.messages) {
			msg_back=res.messages[0];
		} else if (!!res.resultMessage) {
			msg_back=res.resultMessage;
		} else {
			msg_back = '无报错信息';
		}
		var msg = msgs[code] || msg_back;
		return msg;
	},
	ajax: function(options) {

        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        options.async = options.async || true;
        var params = this.formatParams(options.data);

        //创建 - 非IE6 - 第一步
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else { //IE6及其以下版本浏览器
            var xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        //接收 - 第三步
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        }

        //连接 和 发送 - 第二步
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, options.async);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", options.url, options.async);
            //设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            //console.info(xhr);
            xhr.send(params);
        }
    },

    formatParams: function (data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("v=" + Math.random()).replace(".",""));
        return arr.join("&");
    },
    isApp:function(){
        var ua = window.navigator.userAgent;//获取ua
        if(ua.indexOf("MongoToC")>=0){
           return true;
        }else{
            return false;
        }
    },
    
	/**
	 * 跳转404页面
	 * @param {String} code 错误代码
	 */
	goNotFound: function(code) {
		if ( typeof code == 'object' || isNaN(code) ) {
			code = '';
		}
		
//		window.location.href = code ? 'http://h.jia.sit.com/errorMsg404.htm?code=' + code : 'http://h.jia.sit.com/errorMsg404.htm';
		window.location.href = code ? process.env.HOST_NAME + '/errorMsg404.htm?code=' + code : process.env.HOST_NAME + '/errorMsg404.htm';
	},
    getPlate:function(num){
        var data = {
            310000:"沪",
            110000:"京",
            120000:"津",
            130000:"冀",
            140000:"晋",
            150000:"蒙",
            210000:"辽",
            220000:"吉",
            230000:"黑",
            320000:"苏",
            330000:"浙",
            340000:"皖",
            350000:"闽",
            360000:"赣",
            370000:"鲁",
            410000:"豫",
            420000:"鄂",
            430000:"湘",
            440000:"粤",
            450000:"桂",
            460000:"琼",
            500000:"渝",
            510000:"川",
            520000:"贵",
            530000:"云",
            540000:"藏",
            610000:"陕",
            620000:"甘",
            630000:"青",
            640000:"宁",
            650000:"新"
        }
        return num?data[num]:'沪';
	},
	getProvince:function(num){
		var numId = num + '0000';
        var data = {
            310000:"上海市",
            110000:"北京市",
            120000:"天津市",
            130000:"河北省",
            140000:"山西省",
            150000:"内蒙古自治区",
            210000:"辽宁省",
            220000:"吉林省",
            230000:"黑龙江省",
            320000:"江苏省",
            330000:"浙江省",
            340000:"安徽省",
            350000:"福建省",
            360000:"江西省",
            370000:"山东省",
            410000:"河南省",
            420000:"湖北省",
            430000:"湖南省",
            440000:"广东省",
            450000:"广西省",
            460000:"海南省",
            500000:"重庆市",
            510000:"四川省",
            520000:"贵州省",
            530000:"云南省",
            540000:"西藏自治区",
            610000:"陕西省",
            620000:"甘肃省",
            630000:"青海省",
            640000:"宁夏回族自治区",
            650000:"新疆维吾尔自治区"
        }
       	for(var i in data){
       		if(i == numId){
       			var provName = data[i];
       		}
       	}
        return provName;
    },
    getappVersion:function(){
        if(this.isApp()){
            var ua =  JSON.parse(window.navigator.userAgent);
            var appversion = ua.appVersion?ua.appVersion.replace('.',''):"未定义";        
            return appversion;
        }else{
            return 1;
        }

    },
    getCookie:function(cookie_name){ 
        var allcookies = document.cookie;  
        var cookie_pos = allcookies.indexOf(cookie_name);  
        if (cookie_pos != -1){
            cookie_pos += cookie_name.length + 1;
            var cookie_end = allcookies.indexOf(";", cookie_pos);
            if (cookie_end == -1){    
            cookie_end = allcookies.length;
            } 
            var value = unescape(allcookies.substring(cookie_pos, cookie_end));  
        }  
        return value;  
    },
    urlMap: function(env) {
        var env = process.env.NODE_ENV;
        var urlMap = {
            'production':'chexiang.com',
            'preview':'chexiangpre.com',
            'integration':'chexiangsit.com'
        }
        return urlMap[env];
    }

};

// common.ajax({
//     url: common.isdev()+"/user/checkLogin.htm",
//     type: "POST",
//     async:false,
//     dataType: "json",
//     success: function (response, xml) {
//         console.info('success');
//         // 此处放成功后执行的代码
//     },
//     fail: function (status) {
//         // 此处放失败后执行的代码
//     }
// });